package org.jeecg.modules.mes.order.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.mes.client.BomClient;
import org.jeecg.modules.mes.order.entity.ExpApplyBill;
import org.jeecg.modules.mes.order.entity.MesOrderProduce;
import org.jeecg.modules.mes.order.entity.MesOrderSale;
import org.jeecg.modules.mes.order.entity.MesSaleItem;
import org.jeecg.modules.mes.order.service.IMesOrderProduceService;
import org.jeecg.modules.mes.order.service.IMesOrderSaleService;
import org.jeecg.modules.mes.order.service.IMesSaleItemService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 订单管理—销售订单
 * @Author: jeecg-boot
 * @Date: 2020-10-19
 * @Version: V1.0
 */
@Api(tags = "订单管理—销售订单")
@RestController
@RequestMapping("/order/mesOrderSale")
@Slf4j
public class MesOrderSaleController extends JeecgController<MesOrderSale, IMesOrderSaleService> {

    @Autowired
    private IMesOrderProduceService mesOrderProduceService;

    @Autowired
    private IMesOrderSaleService mesOrderSaleService;

    @Autowired
    private IMesSaleItemService mesSaleItemService;

    @Autowired
    BomClient bomClient;

    @Autowired
    RedisUtil redisUtil;


    /*---------------------------------主表处理-begin-------------------------------------*/

    /**
     * 分页列表查询
     *
     * @param mesOrderSale
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "订单管理—销售订单-分页列表查询")
    @ApiOperation(value = "订单管理—销售订单-分页列表查询", notes = "订单管理—销售订单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(MesOrderSale mesOrderSale,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<MesOrderSale> queryWrapper = QueryGenerator.initQueryWrapper(mesOrderSale, req.getParameterMap());
        Page<MesOrderSale> page = new Page<MesOrderSale>(pageNo, pageSize);
        IPage<MesOrderSale> pageList = mesOrderSaleService.page(page, queryWrapper);
        List<MesOrderSale> saleList = pageList.getRecords();
        if (saleList != null) {
            //如果上传关务系统的状态为空，则设置状态为0（预防作用）
            for (MesOrderSale sale : saleList) {
                if (StringUtils.isBlank(sale.getImportState())) {
                    sale.setImportState("0");//设置上传关务系统的状态为0
                    mesOrderSaleService.updateById(sale);
                }
                //通过销售订单id，获取销售订单子表数据
                String orderId = sale.getId();
                QueryWrapper<MesSaleItem> wrapper = new QueryWrapper<>();
                wrapper.eq("saleorder_id", orderId);
                List<MesSaleItem> saleItemList = mesSaleItemService.list(wrapper);
                if (saleItemList.size() != 0) {
                    float totalPrice = 0;
                    for (MesSaleItem saleItem : saleItemList) {
                        //如果销售明细的价格不为空，则它们的总和为销售订单的总价
                        if (StringUtils.isNotBlank(saleItem.getAccount())) {
                            String grossPrice = saleItem.getAccount();//单价
                            totalPrice += Float.parseFloat(grossPrice);
                        }
                    }
                    sale.setGrossPrice(totalPrice + "");//总价
                    mesOrderSaleService.updateById(sale);
                }
            }
        }
        IPage<MesOrderSale> pageList1 = mesOrderSaleService.page(page, queryWrapper);
        return Result.ok(pageList1);
    }

    @AutoLog(value = "出口申请单-生成")
    @ApiOperation(value="出口申请单-生成", notes="根据销售单id生成出口申请单")
    @GetMapping(value = "/generateExp")
    public Result<?> generateImport(@RequestParam(name="saleId",required=true) String saleId){
        MesOrderSale sale = mesOrderSaleService.getById(saleId);
        if (sale!=null) {
                if(StringUtils.isBlank(sale.getState())||!"完成".equals(sale.getState())){
                    return Result.error("该销售订单还未完成，不能生成出口单！");
                }
                if("1".equals(sale.getImportState())){//是否导入关务系统，若已导入，则为1,反之为0
                    return Result.error("已生成过出口申请单！");
                }
                QueryWrapper<MesSaleItem> wrapper = new QueryWrapper<>();
                wrapper.eq("saleorder_id", saleId);
                List<MesSaleItem> saleItemList = mesSaleItemService.list(wrapper);
                if (saleItemList.size() != 0) {
                    List<ExpApplyBill> billlist = new ArrayList<>();
                    int count1 = 0;
                    for (MesSaleItem saleItem : saleItemList) {
                        count1 += 1;
                        //实例化format，格式为“000”
                        Format f1 = new DecimalFormat("000");
                        //将1变为001
                        String count = f1.format(count1);

                        ExpApplyBill expApplyBill = new ExpApplyBill();
                        expApplyBill.setGwId(IdUtil.simpleUUID());
                        expApplyBill.setOutBillNo(sale.getOrderCode());//出货单号
                        expApplyBill.setImgExgFlag(saleItem.getImgExgFlag());//物料标记
                        expApplyBill.setItemNo(count1);
                        expApplyBill.setMaterial(saleItem.getMaterielCode());//料号
                        expApplyBill.setMaterialName(saleItem.getMaterielName());//品名
                        expApplyBill.setMaterialGuige(saleItem.getMaterielGauge());//规格
                        expApplyBill.setOptLock(0);
                        SimpleDateFormat Dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
                        String dateTime = Dateformat.format(new Date());
                        expApplyBill.setSectionNo(dateTime + "001");//批次号
                        expApplyBill.setCompanyCode("500666002U");//公司编码
//                        expApplyBill.setUploadDate(new java.util.Date());//改为上传关务的时候修改该字段
                        if (StringUtils.isBlank(saleItem.getAccount())) {
                            saleItem.setAccount("0");
                        }
                        expApplyBill.setPrice(Double.parseDouble(saleItem.getAccount()));//企业单件
                        if (StringUtils.isBlank(sale.getGrossPrice())) {
                            sale.setGrossPrice("0");
                        }
                        expApplyBill.setAmount(Double.parseDouble(sale.getGrossPrice()));//企业总价
                        expApplyBill.setCurr(sale.getCurrency());//币制
                        expApplyBill.setCompanyMergerKey("");
                        if (StringUtils.isEmpty(saleItem.getCompanyCode())) {
                            SimpleDateFormat Dateformatter = new SimpleDateFormat("yyyy/M/d");
                            String docketTime = Dateformatter.format(new Date());
                            expApplyBill.setInvoiceDate(docketTime);//票据日期
                        } else {
                            expApplyBill.setInvoiceDate(saleItem.getCompanyCode());//票据日期
                        }
                        if (StringUtils.isBlank(saleItem.getPalletNum())) {
                            saleItem.setPalletNum("0");
                        }
                        expApplyBill.setPalletNum(Integer.parseInt(saleItem.getPalletNum()));//板数
                        if (StringUtils.isBlank(saleItem.getPcs())) {
                            saleItem.setPcs("0");
                        }
                        expApplyBill.setPcs(Integer.parseInt(saleItem.getPcs()));//件数
                        expApplyBill.setWrap(saleItem.getWrap());//包装种类
                        expApplyBill.setContainerNo(saleItem.getContainerNo());//箱号
                        if (StringUtils.isBlank(saleItem.getOrderNum())) {
                            saleItem.setOrderNum("0.00");
                        }
                        expApplyBill.setQty(Double.parseDouble(saleItem.getOrderNum()));//企业数量
                        if (StringUtils.isBlank(saleItem.getNetWeight())) {
                            saleItem.setNetWeight("0.00");
                        }
                        expApplyBill.setNetWeight(Double.parseDouble(saleItem.getNetWeight()));//净重
                        if (StringUtils.isBlank(saleItem.getGrossWeight())) {
                            saleItem.setGrossWeight("0.00");
                        }
                        expApplyBill.setGrossWeight(Double.parseDouble(saleItem.getGrossWeight()));//毛重
                        expApplyBill.setScmCoc(sale.getSaleName());//客户/供应商
                        expApplyBill.setZextendItemField1(saleItem.getZextendItemField1());//立方数
                        expApplyBill.setDestinationCountry(saleItem.getDestinationCountry());//目的国
                        expApplyBill.setClientCode(saleItem.getClientCode());
                        expApplyBill.setProductCode(saleItem.getProductCode());
                        expApplyBill.setExpApplyState("未上传");
                        billlist.add(expApplyBill);

                    }
                    //更改销售订单主表状态为1：已上传
                    sale.setImportState("1");
                    mesOrderSaleService.saveExpUpdateState(sale,billlist);
                    System.err.println("出口申请单生成完成---");
                }else {
                    return Result.error("没有找到销售订单子表的数据！请检查！");
                }
        }else {
            return Result.ok("该销售单已生成出口申请单！");
        }
        return Result.ok("生成出口申请单成功！");
    }

    /*@AutoLog(value = "主数据—出口申请单-导入关务系统")
    @ApiOperation(value = "主数据—出口申请单-导入关务系统", notes = "主数据—出口申请单-导入关务系统")
    @PostMapping(value = "/importSaleSqlServer")
    public Result<?> importSaleSqlServer() {
        QueryWrapper<MesOrderSale> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("import_state", "0");//是否导入关务系统，若已导入，则为1,反之为0
        queryWrapper.eq("state", "完成");
        List<MesOrderSale> saleList = mesOrderSaleService.list(queryWrapper);
        System.err.println(saleList);
        System.err.println(saleList.size());
        if (saleList.size() != 0) {
            for (MesOrderSale sale : saleList) {
                String saleId = sale.getId();
                QueryWrapper<MesSaleItem> wrapper = new QueryWrapper<>();
                wrapper.eq("saleorder_id", saleId);
                List<MesSaleItem> saleItemList = mesSaleItemService.list(wrapper);
                if (saleItemList.size() != 0) {
                    int count1 = 0;
                    for (MesSaleItem saleItem : saleItemList) {
                        count1 += 1;
                        //实例化format，格式为“000”
                        Format f1 = new DecimalFormat("000");
                        //将1变为001
                        String count = f1.format(count1);
                        try {
                            // 加载sqlserver的驱动类
                            Class.forName("net.sourceforge.jtds.jdbc.Driver");
                            String url = "jdbc:jtds:sqlserver://192.168.10.80/idb";

                            String username = "sa";//用户名
                            String password = "yzy20170907";//密码
                            try {
                                Connection conn = DriverManager.getConnection(url, username, password);
                                conn.setAutoCommit(false);
                                Statement stmt = conn.createStatement();
                                String sql = "";
                                PreparedStatement ps = null;
                                sql = "INSERT INTO ExpApplyBillDBTemp (id,outBillNo,imgExgFlag,itemNo,material,optLock,sectionNo,companyCode,uploadDate,price,amount,curr,companyMergerKey,invoiceDate,palletNum,pcs,wrap,containerNo,qty,netWeight,grossWeight,scmCoc,zextendItemField1,destinationCountry) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
                                ps = conn.prepareStatement(sql);
                                ps.setString(1, IdUtil.simpleUUID());//id
                                ps.setString(2, sale.getOrderCode());//出货单号
                                ps.setString(3, saleItem.getImgExgFlag());//物料标记
                                ps.setInt(4, count1);//项号
                                ps.setString(5, saleItem.getMaterielCode());//料号
                                ps.setInt(6, 0);//乐观锁
                                SimpleDateFormat Dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
                                String dateTime = Dateformat.format(new Date());
                                ps.setString(7, dateTime + "001");//批次号
                                ps.setString(8, "500666002U");//公司编码
                                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                String date = formatter.format(new java.util.Date());
                                ps.setString(9, date);//上传时间
                                ps.setString(10, saleItem.getAccount());//企业单件
                                ps.setString(11, sale.getGrossPrice());//企业总价
                                ps.setString(12, sale.getCurrency());//币制
                                ps.setString(13, "");//企业关键合并key
                                if (StringUtils.isEmpty(saleItem.getCompanyCode())) {
                                    SimpleDateFormat Dateformatter = new SimpleDateFormat("yyyy/M/d");
                                    String docketTime = Dateformatter.format(new Date());
                                    ps.setString(14, docketTime);//票据日期
                                } else {
                                    ps.setString(14, saleItem.getCompanyCode());//票据日期
                                }
                                ps.setString(15, saleItem.getPalletNum());//板数
                                ps.setString(16, saleItem.getPcs());//件数
                                ps.setString(17, saleItem.getWrap());//包装种类
                                ps.setString(18, saleItem.getContainerNo());//箱号
                                ps.setString(19, saleItem.getOrderNum());//企业数量
                                ps.setString(20, saleItem.getNetWeight());//净重
                                ps.setString(21, saleItem.getGrossWeight());//毛重
                                ps.setString(22, sale.getSaleName());//客户/供应商
                                ps.setString(23, saleItem.getZextendItemField1());//立方数
                                ps.setString(24, saleItem.getDestinationCountry());//目的国
                                ps.executeUpdate();
                                conn.commit();
                                //更改销售订单主表状态为1：已上传
                                sale.setImportState("1");
                                mesOrderSaleService.updateById(sale);
                                System.err.println("出口申请单导入完成---");

                                if (ps != null) { // 关闭声明
                                    try {
                                        ps.close();
                                    } catch (SQLException e) {
//										 e.printStackTrace();
                                        log.error(e.getMessage(), e);
                                    }
                                }
                                if (stmt != null) { // 关闭声明
                                    try {
                                        stmt.close();
                                    } catch (SQLException e) {
//										 e.printStackTrace();
                                        log.error(e.getMessage(), e);
                                    }
                                }
                                if (conn != null) { // 关闭连接对象
                                    try {
                                        conn.close();
                                    } catch (SQLException e) {
//										 e.printStackTrace();
                                        log.error(e.getMessage(), e);
                                    }
                                }
                            } catch (SQLException se) {
//								 se.printStackTrace();
                                log.error(se.getMessage(), se);
                                return Result.error("关务系统连接失败！请联系管理员检查！");
                            }
                        } catch (ClassNotFoundException e) {
                            log.error(e.getMessage(), e);
                            return Result.error("找不到驱动程序类 ，加载驱动失败！");
                        }
                    }
                } else {
                    return Result.error("没有找到销售订单子表的数据！请检查！");
                }
            }
        } else {
            return Result.ok("数据已全部导入关务系统！");
        }
        return Result.ok(" 关务系统导入成功！");
    }*/

    /**
     * 添加
     *
     * @param mesOrderSale
     * @return
     */
    @AutoLog(value = "订单管理—销售订单-添加")
    @ApiOperation(value = "订单管理—销售订单-添加", notes = "订单管理—销售订单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MesOrderSale mesOrderSale) {
        //销售订单添加时，设置订单状态为：未完成，上传状态为0：未上传
        LambdaQueryWrapper<MesOrderSale> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MesOrderSale::getOrderCode, mesOrderSale.getOrderCode().replaceAll(" ", ""));
        MesOrderSale order = mesOrderSaleService.getOne(wrapper);
        if (Objects.isNull(order)) {
            mesOrderSale.setState("未完成");
            mesOrderSale.setImportState("0");
            mesOrderSaleService.save(mesOrderSale);
            return Result.ok("添加成功！");
        } else {
            return Result.error("订单号重复，请检查");
        }

    }

    /**
     * 远程调用模块，通过id获取销售订单数据
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryMesSaleOrderById")
    public MesOrderSale queryMesSaleOrderById(@RequestParam(name = "id", required = true) String id) {
        MesOrderSale mesOrderSale = mesOrderSaleService.getById(id);
        return mesOrderSale;
    }

    /**
     * 远程调用模块，通过Code获取销售订单数据
     *
     * @param code
     * @return
     */
    @GetMapping(value = "/queryMesSaleOrderByCode")
    public List<MesOrderSale> queryMesSaleOrderByCode(@RequestParam(name = "code", required = true) String code) {
        QueryWrapper<MesOrderSale>  queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(MesOrderSale::getOrderCode,code);
        List<MesOrderSale> mesOrderSales = mesOrderSaleService.list(queryWrapper);
        return mesOrderSales;
    }

    /**
     * 远程调用模块，修改销售订单主表
     *
     * @param mesOrderSale
     * @return
     */
    @PutMapping(value = "/editSaleOrder")
    public String editSaleOrder(@RequestBody MesOrderSale mesOrderSale) {
        mesOrderSaleService.updateById(mesOrderSale);
        return "编辑成功！";
    }

    /**
     * 编辑
     *
     * @param mesOrderSale
     * @return
     */
    @AutoLog(value = "订单管理—销售订单-编辑")
    @ApiOperation(value = "订单管理—销售订单-编辑", notes = "订单管理—销售订单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MesOrderSale mesOrderSale) {
        if (mesOrderSale.getState().equals("完成")) {
            QueryWrapper<MesSaleItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("saleorder_id", mesOrderSale.getId());
            List<MesSaleItem> saleItemList = mesSaleItemService.list(queryWrapper);
            if (saleItemList.size() != 0) {
                for (MesSaleItem saleItem : saleItemList) {
                    saleItem.setState("完成");
                    mesSaleItemService.updateById(saleItem);
                }
            }
        }
        mesOrderSaleService.updateById(mesOrderSale);
        return Result.ok("编辑成功!");
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—销售订单-通过id删除")
    @ApiOperation(value = "订单管理—销售订单-通过id删除", notes = "订单管理—销售订单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        //判断是否有生产订单，有的话不能删除
        QueryWrapper<MesOrderProduce> mesOrderProduceQueryWrapper = new QueryWrapper<>();
        mesOrderProduceQueryWrapper.eq("saleorder_id",id);
        List<MesOrderProduce> list = mesOrderProduceService.list(mesOrderProduceQueryWrapper);
        if (list.size()>0){
            return Result.error("已创建生产订单，无法删除!");
        }

        mesOrderSaleService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "订单管理—销售订单-批量删除")
    @ApiOperation(value = "订单管理—销售订单-批量删除", notes = "订单管理—销售订单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> ls=Arrays.asList(ids.split(","));
        //判断是否有生产订单，有的话不能删除
        for (String id:ls) {
            QueryWrapper<MesOrderProduce> mesOrderProduceQueryWrapper = new QueryWrapper<>();
            mesOrderProduceQueryWrapper.eq("saleorder_id",id);
            List<MesOrderProduce> list = mesOrderProduceService.list(mesOrderProduceQueryWrapper);
            if (list.size()>0){
                return Result.error(list.get(0).getSaleorderCode()+"已创建生产订单，无法删除!请重新选择！");
            }
        }
        this.mesOrderSaleService.delBatchMain(ls);
        return Result.ok("批量删除成功!");
    }


    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesOrderSale mesOrderSale) {
        return super.exportXls(request, mesOrderSale, MesOrderSale.class, "订单管理—销售订单");
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesOrderSale.class);
    }
    /*---------------------------------主表处理-end-------------------------------------*/

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—销售订单子表-通过iD查询(自己写的)")
    @ApiOperation(value = "订单管理—销售订单子表-通过ID查询(自己写的)", notes = "订单管理—采购订单子表-通过ID查询(自己写的)")
    @GetMapping(value = "/queryMesSaleItemById")
    public MesSaleItem queryMesSaleItemById(@RequestParam(name = "id", required = true) String id) {
        MesSaleItem mesSaleItem = mesSaleItemService.getById(id);
        return mesSaleItem;
    }

    /*--------------------------------子表处理-订单管理—销售订单子表-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    @AutoLog(value = "订单管理—销售订单子表-通过主表ID查询")
    @ApiOperation(value = "订单管理—销售订单子表-通过主表ID查询", notes = "订单管理—销售订单子表-通过主表ID查询")
    @GetMapping(value = "/listMesSaleItemByMainId")
    public Result<?> listMesSaleItemByMainId(MesSaleItem mesSaleItem,
                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                             HttpServletRequest req) {
        System.err.println(mesSaleItem);
        QueryWrapper<MesSaleItem> queryWrapper = QueryGenerator.initQueryWrapper(mesSaleItem, req.getParameterMap());
        Page<MesSaleItem> page = new Page<MesSaleItem>(pageNo, pageSize);
        IPage<MesSaleItem> pageList = mesSaleItemService.page(page, queryWrapper);
//        if(pageList.getTotal() == 0){
//        	System.err.println(mesSaleItem.getSaleorderId());
//        	MesOrderSale mesOrderSale = mesOrderSaleService.getById(mesSaleItem.getSaleorderId());
//        	mesOrderSale.setState("已完成");
//        	mesOrderSaleService.updateById(mesOrderSale);
//		}
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param mesSaleItem
     * @return
     */
    @AutoLog(value = "订单管理—销售订单子表-添加")
    @ApiOperation(value = "订单管理—销售订单子表-添加", notes = "订单管理—销售订单子表-添加")
    @PostMapping(value = "/addMesSaleItem")
    public Result<?> addMesSaleItem(@RequestBody MesSaleItem mesSaleItem) {
        String ordernum = mesSaleItem.getOrderNum();
        if (StringUtils.isNotBlank(ordernum)) {
            mesSaleItem.setUndeliveryNum(ordernum);
        }
        mesSaleItem.setState("未完成");
        mesSaleItemService.save(mesSaleItem);
        System.err.println(mesSaleItem.getSaleorderId());
        MesOrderSale mesOrderSale = mesOrderSaleService.getById(mesSaleItem.getSaleorderId());
        mesOrderSale.setState("未完成");
        mesOrderSaleService.updateById(mesOrderSale);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mesSaleItem
     * @return
     */
    @AutoLog(value = "订单管理—销售订单子表-编辑")
    @ApiOperation(value = "订单管理—销售订单子表-编辑", notes = "订单管理—销售订单子表-编辑")
    @PutMapping(value = "/editMesSaleItem")
    public Result<?> editMesSaleItem(@RequestBody MesSaleItem mesSaleItem) {
        String ordernum = mesSaleItem.getOrderNum();
        if (StringUtils.isNotBlank(ordernum)) {
            mesSaleItem.setUndeliveryNum(ordernum);
        }
        mesSaleItemService.updateById(mesSaleItem);
        return Result.ok("编辑成功!");
    }

    @PutMapping(value = "/editSaleItem")
    public String editSaleItem(@RequestBody MesSaleItem mesSaleItem) {
        mesSaleItemService.updateById(mesSaleItem);
        return "编辑成功!";
    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—销售订单-通过id查询")
    @ApiOperation(value = "订单管理—销售订单-通过id查询", notes = "订单管理—销售订单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        MesOrderSale mesOrderSale = mesOrderSaleService.getById(id);
        if (mesOrderSale == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(mesOrderSale);

    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单管理—销售订单子表-通过id删除")
    @ApiOperation(value = "订单管理—销售订单子表-通过id删除", notes = "订单管理—销售订单子表-通过id删除")
    @DeleteMapping(value = "/deleteMesSaleItem")
    public Result<?> deleteMesSaleItem(@RequestParam(name = "id", required = true) String id) {
        mesSaleItemService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "订单管理—销售订单子表-批量删除")
    @ApiOperation(value = "订单管理—销售订单子表-批量删除", notes = "订单管理—销售订单子表-批量删除")
    @DeleteMapping(value = "/deleteBatchMesSaleItem")
    public Result<?> deleteBatchMesSaleItem(@RequestParam(name = "ids", required = true) String ids) {
        this.mesSaleItemService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
    @RequestMapping(value = "/exportMesSaleItem")
    public ModelAndView exportMesSaleItem(HttpServletRequest request, MesSaleItem mesSaleItem) {
        // Step.1 组装查询条件
        QueryWrapper<MesSaleItem> queryWrapper = QueryGenerator.initQueryWrapper(mesSaleItem, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<MesSaleItem> pageList = mesSaleItemService.list(queryWrapper);
        List<MesSaleItem> exportList = null;

        // 过滤选中数据
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        } else {
            exportList = pageList;
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "订单管理—销售订单子表"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, MesSaleItem.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("订单管理—销售订单子表报表", "导出人:" + sysUser.getRealname(), "订单管理—销售订单子表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 导入
     *
     * @return
     */
    @RequestMapping(value = "/importMesSaleItem/{mainId}")
    public Result<?> importMesSaleItem(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MesSaleItem> list = ExcelImportUtil.importExcel(file.getInputStream(), MesSaleItem.class, params);
                for (MesSaleItem temp : list) {
                    temp.setSaleorderId(mainId);
                }
                long start = System.currentTimeMillis();
                mesSaleItemService.saveBatch(list);
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-订单管理—销售订单子表-end----------------------------------------------*/


}
